<!--
表格的内容区域
Props：
data：数据源 数组
showIndex:是否显示索引 布尔
Event:
Chang:记录发生移动触发，参数是移动后的数组

动画效果？
-->
<template>
  <div>
    <!-- 表格区域 -->
    <the-table :data="data"
               :showPage="false"
               :height="height"
               :isOrder="{show:showIndex}">
      <slot></slot>
      <el-table-column label="移动">
        <template slot-scope="scope">
          <el-button @click="moveItem('up',scope.row)"
                     circle
                     size="mini"
                     icon="el-icon-arrow-up"></el-button>
          <el-button @click="moveItem('down',scope.row)"
                     circle
                     size="mini"
                     icon="el-icon-arrow-down"></el-button>
        </template>
      </el-table-column>
    </the-table>
  </div>
</template>

<script>
export default {
  name: 'SortTable',
  props: {
    data: {
      type: Array,
      default: () => []
    },
    // 是否显示序号
    showIndex: {
      type: Boolean,
      default: true
    },
    height: String
  },
  data () {
    return {
      dataList: []
    }
  },
  methods: {
    moveItem (direction, row) {
      // 获取目标记录的索引
      const rowIdx = this.data.indexOf(row)
      if (rowIdx === -1) return;
      // 通过direction决定记录的排序

      //保存原数组
      const sortList = [...this.data]

      if (direction === 'up' && rowIdx !== 0) {

        // 交换item
        this.swap(sortList, rowIdx, rowIdx - 1)
      }
      if (direction === 'down' && rowIdx !== row.length - 1) {

        // 交换item
        this.swap(sortList, rowIdx, rowIdx + 1)
      }
      return this.$emit('change', sortList)

    },
    swap (arr, i, j) {
      const t = arr[j]
      arr[j] = arr[i]
      arr[i] = t
    }
  },
  mounted () {
    //保存父组件的数据
    this.dataList = [...this.data]
  }
}
</script>

<style scoped>
</style>